package gsde.springboot.eurekaserver;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpEntity;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.HttpHeaders;
import javax.xml.ws.ServiceMode;
import java.util.HashMap;
import java.util.Map;

@Service
public class GsdeHttpService {

    @Bean
    public RestTemplate rest() {
        return new RestTemplate();
    }

    @Autowired
    RestTemplate restTemplate;

    /**
     * http post 命令
     * @param url
     * @param map
     * @return
     */
    public Map<String, Object> postHttp(String url, Map<String, Object> params) {

        if (restTemplate == null) {
            restTemplate = new RestTemplate();
        }
        HttpHeaders headers = new HttpHeaders();

        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        headers.setContentType(MediaType.APPLICATION_JSON);//设置参数类型和编码


        HttpEntity<Map<String,Object>> request = new HttpEntity<>(params, headers);//包装到HttpEntity


        Map<String, Object> res = null;
        try {
            res = restTemplate.postForObject(url, request, Map.class);

            return res;
        } catch (Exception e) {
            System.out.println(e.toString());
        }

        return null;
    }

    /**
     * http get 操作
     * @param url
     * @param params 参数
     * @return
     */
    public Map<String, Object> getHttp(String url, Map<String, Object> params)
    {
        if (restTemplate == null) {
            restTemplate = new RestTemplate();
        }
            Map<String, Object> res = null;
        try {
            res = restTemplate.getForObject(url, Map.class, params);
        }
        catch (Exception e)
        {
            res = null;
        }

        return res;
        }
}
